<script lang="ts">
	import SimpleEditor from '$lib/components/editor/SimpleEditor.svelte';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import EditorJS from '@editorjs/editorjs';

	interface Props {
		roadmapId: string;
		onCancel: () => void;
		onOk: () => void;
	}
	const props: Props = $props();

	let name = $state('');
	let contentEditor: EditorJS | null = $state(null);

	async function publishAsk() {
		if (contentEditor == null || userStore.userSession == null) {
			return;
		}

		const contentData = await contentEditor.save();
		if (contentData.blocks.length == 0) {
			appStore.addToastMessage({
				level: 'error',
				content: '请输入提问内容',
				keepTime: 2000
			});
			return;
		}

		//创建thread
		const threadRes = await callApi(
			appStore.roadmapQaApiClient.addThread({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				basicInfo: {
					name: name
				}
			}).response
		);
		//创建内容
		await callApi(
			appStore.roadmapQaApiClient.addContent({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				threadId: threadRes.threadId,
				content: JSON.stringify(contentData)
			}).response
		);
		//设置最后访问时间
		await callApi(
			appStore.roadmapQaApiClient.viewThread({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				threadId: threadRes.threadId
			}).response
		);
		props.onOk();
	}
</script>

<dialog class="modal modal-open bg-transparent!">
	<div class="modal-box w-[800px] max-w-none">
		<button
			class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
			onclick={() => props.onCancel()}>✕</button
		>
		<h3 class="text-lg font-bold">发布提问</h3>

		<div class="max-h-[60vh] overflow-y-auto pr-[10px] flex-col space-y-4 pt-[20px]">
			<label class="label w-full">
				<span class="label w-[80px] text-right inline-block pr-[10px]">标题:</span>
				<input type="text" class="input w-full" bind:value={name} />
			</label>
			<h4 class="text-base font-bold">内容</h4>
			<SimpleEditor
				sizeClass="min-h-[300px] border-2 border-base-200 max-h-[300px]"
				placeholder="请输入提问内容"
				onInit={(tmpEditor) => (contentEditor = tmpEditor)}
			/>
		</div>
		<div class="modal-action">
			<button class="btn" onclick={() => props.onCancel()}>取消</button>
			<button class="btn btn-primary" disabled={name.trim() == ''} onclick={() => publishAsk()}
				>发布</button
			>
		</div>
	</div>
</dialog>
